package com.zhugang.week06;

import java.util.ArrayList;
import java.util.List;

/**
 * @program algorithms
 * @description: isValidBST
 * @author: chanzhugang
 * @create: 2022/07/18 12:08
 */
public class IsValidBST2 {

    /**
     * 98 验证二叉搜索树：中序遍历有序
     *
     * @param root
     * @return
     */
    List<Integer> list = new ArrayList<>();

    public boolean isValidBST(TreeNode root) {
        // 中序遍历，递增就是二叉搜索树
        dfs(root);
        // 判断集合是否有序递增
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i) > list.get(i + 1)) {
                return false;
            }
        }
        return true;
    }

    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        list.add(root.val);
        dfs(root.right);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}